<?php

namespace App\Http\Controllers\Api\Third;

use App\Http\Controllers\Api\Third\CommonApiController;
use DB;

//山东带电作业内网接口   局域网才访问才可以，外网无法访问（浏览器限制）
class SdDdzyApiController extends CommonApiController
{
    // 1、服务器地址:
    private $BaseUrl = "http://ip:port/";
    private $thirdId = 0;
    private $thirdMap = [];
    private $orgs = [];
    public function __construct($third){
        // dd($third);
        $this->BaseUrl = $third->base_url;
        $this->thirdId = $third->id;
    }

    private function send232Data($params){
        $api = array_get($params,'api','');
        $param = array_get($params,'params',[]);
        $return = array_get($params,'return','');
        $toData = [
            'api'=>$api,
            'param'=>is_array($param) ? json_encode($param) : $param,
            'return'=>$return,
        ];
        return '$&$'.json_encode($toData).'$|$';
    }

    //7、获取送检机构信息,这里不需要搜索，所以不用将name设置label，id设置value
    public function getOrgTree(){
        return $this->requestData(['api'=>'/api/testdata/GetDepartmentItems'],function ($data){
            array_walk($data,function(&$item){
                $item = array_change_key_case($item,CASE_LOWER);
            });
            return collect($data)->keyBy(function ($item){
                return $item['id'];
            })->toArray();
        });
    }

    //2、获取待检工具项目信息
    public function getGqjBookTestInfo($thirdMap){
        info('SdDdzyApiController');
        $this->thirdMap = $thirdMap;
        $thirdId = $this->thirdId;
        $params = request('params',[]);
        return $this->requestData(['api'=>'/api/testdata/toolinfos','params'=>$params],'insert_third_data');
    }
    private function requestData(
        $params=['api'=>'','params'=>[],'return'=>''],
        $sucBakFunc=''
    ){
        // if (isAdmin()) {
        //     if(strstr($params['api'],'toolinfos')){
        //         $res = file_get_contents(__DIR__.'/sdddzy_new.txt');
        //     }else if(strstr($params['api'],'GetDepartmentItems')){
        //         $res = file_get_contents(__DIR__.'/sdddzy_org.txt');
        //     }else{
        //         $res = '$&${"api": "/api/testdata/submitinfo","param": "","return": "{\"statusCode\": 200,\"data\": 200,\"succeeded\": true,\"errors\": \"\",\"extras\": \"\",\"timestamp\": 1660015866160}"}$|$';
        //     }
        // }else{
            $postData = $this->send232Data($params);
            // dd($postData);
            $res = curl($this->BaseUrl, urlencode($postData));
        // }
        if(!$res){
            return 'COM口连接异常，请检查！！！';
        }
        $res = ltrim($res,'$&$');
        $res = rtrim($res,'$|$');
        $res = json_decode($res,true);
        $res = json_decode(str_replace('\'','"',data_get($res,'return','')),true);
        if (!$res) {
            return '服务请求异常，请检查！！！';
        }
        $status = data_get($res,'statusCode',0);
        if ($status != '200') {
            return data_get($res,'errors','调取失败，请检查！');
        }
        $data = data_get($res,'data',[]);
        if($sucBakFunc){
            if(is_string($sucBakFunc)) return $this->$sucBakFunc ($data);
            return $sucBakFunc ($data);
        }
        return $data ?: 1;
    }

    /*获取基础数据信息*/
    public function getToolItems(){
        $data = $this->getTestItems();
        // $data = $this->requestData(['api'=>'/api/testdata/getbaseitems']);
        $ret = 0;
        if ($data && is_array($data)){
            $itemsNow = DB::table('a_third_testitem')->where('third_id',$this->thirdId)->get()->keyBy(function ($item)
                {
                    return $item->tool_id.'-'.$item->item_id;                
                })->toArray();
            // dd($itemsNow);
            $inData = [];
            foreach ($data as $itemId => $item) {
                if (!isset($itemsNow['-'.$itemId])) {
                    $inData[] = [
                        'third_id'=>$this->thirdId,
                        'tool_name'=>'',
                        'tool_id'=>'',
                        'item_name'=>$item['name'],
                        'item_id'=>$itemId,
                        'data_keys'=>json_encode($item['upload']),
                    ];
                }
            }
            // dd($inData);
            $ret = DB::table('a_third_testitem')->insert($inData);
        }
        return (int)$ret;
    }

    /*根据送检机构ID获取名称层级关系*/
    private function getOrgData($orgId,$data=[]){
        $orgs = $this->orgs;
        $org = array_get($orgs,$orgId,[]);
        if($org){
            $data[0][]= $orgId;
            $data[1][]= $org['name'];
            return $this->getOrgData($org['parentid'],$data);
        }else{
            if ($data) {
                krsort($data[0]);
                krsort($data[1]);
            }
            return $data;
        }
    }

    /**
     * 插入第三方数据到数据库
     * @param $data
     * @param $contract_id
     * @return bool
     */
    private function insert_third_data($data){
        if (!$data) {
            return 0;
        }
        $data2 = [];
        foreach ($data as $v) {
            $v = array_change_key_case($v,CASE_LOWER);
            $data2[$v['rfid']][] = $v;
        }
        $this->orgs = $this->getOrgTree();
        $thirdMap = $this->thirdMap;
        // dd($thirdMap);
        $thirdVols = data_get($thirdMap[0],'third',[]); //额定电压
        // dd($thirdVols);
        $thirdTools = data_get($thirdMap[2],'third',[]); //工器具类型
        $thirdStds = data_get($thirdMap[3],'third',[]); //检测标准
        $thirdItems = array_get(array_get($thirdMap,4,[]),'third',[]); //检测项目
        $stdToolItems = $this->getStdToolItems();
        $vols= $this->getVolClass(0);
        $total = 0;
        $inData = [];
        foreach ($data2 as $rfid => $items) {
            $v = current($items);
            if($this->isInsert($this->thirdId,$rfid) == 0){
                continue;
            }
            //工器具标准映射检测
            $third_std_num = $v['standardcode'];
            $stdMap = array_get($thirdStds,$third_std_num,[]);
            if (!$stdMap) {
                return $v['categoryname'].$third_std_num.'缺少映射关系！';
            }
            $std_id = $stdMap['sys_id'];
            // dd($stdMap);
            //工器具类型映射检测
            $third_tool_name = $v['categoryname'];
            $toolMap = array_get($thirdTools,$third_tool_name,[]);
            if (!$toolMap) {
                return "{$third_std_num} {$third_tool_name} {$v['categoryid']} 缺少映射关系！";
            }
            $tool_id = $toolMap['sys_id'];
            //+++++++++++ 额定电压映射检测 start +++++++++++++++++++++
                $third_vol = $v['voltagename'];
                $volMap = array_get($thirdVols,$third_vol,[]);
                if (!$volMap) {
                    $vol = array_get($vols,"{$std_id}-{$tool_id}-{$third_vol}",[]); //不对照直接取相同值
                    if(!$vol){ //如果没有相同值，插入新值
                        $std_tool_rel_id = DB::table('a_std_tool_rel')->where(['std_id'=>$std_id,'tool_id'=>$tool_id])->value('id');
                        $vol_id = DB::table('a_voltage_class')->insertGetId(['type'=>0,'std_id'=>$std_id,'tool_id'=>$tool_id,'std_tool_rel_id'=>$std_tool_rel_id,'val'=>$third_vol]);
                        $vols= $this->getVolClass(0);
                    }else{
                        $vol_id = $vol->id;
                    }
                    $sys_vol = $third_vol;
                }else{
                    $sys_vol = array_get($volMap,'sys_name','');
                    $vol = array_get($vols,$std_id.'-'.$tool_id.'-'.$sys_vol,[]); 
                    $vol_id = data_get($vol,'id',0);
                }
            //+++++++++++ 额定电压映射检测 end +++++++++++++++++++++
            //+++++++++++ 检测项目检测 对应主项目id和实际项目id start +++++++++++++++++++++
                //检测系统中是否存在项目
                $sysItems = array_get($stdToolItems,$std_id.'-'.$tool_id,[]);
                $tool_name = $toolMap['sys_name'];
                if(!$sysItems){
                    $std_num = $stdMap['sys_name'];
                    return "请检查{$tool_name}{$std_num}是否存在项目！"; 
                }
                $projecttypeids = $projectids = $projectname = [];
                foreach ($items as $item) { //循环工器具的项目
                    //查找对应item_id  
                    $isMapItem = false; //初始化检测项目是否映射
                    foreach($thirdItems as $thirdItemName => $sysItems2){
                        $thirdItemName = str_replace(' ', '', $thirdItemName);
                        $itemprojectname = str_replace(' ', '', $item['projectname']);
                        // 模糊匹配到对应的项目名称
                        if(strstr($itemprojectname,$thirdItemName) == false) continue;
                        //搜索匹配到主项目id
                        foreach ($sysItems2 as $tool_std_item => $sysItem2) {
                            if ($sysItem2['third_id2'] != $item['projecttypeid'] || !strstr($tool_std_item,$tool_name)) continue;
                            $projecttypeids[] = $sysItem2['sys_id'].'-'.$item['projecttypeid']; //拼接我方实际项目id-第三方主项目id
                            $projectids[] = $sysItem2['sys_id'].'-'.$item['projectid']; //拼接我方实际项目id-第三方实际项目id
                            $projectname[] = $thirdItemName;
                            $isMapItem = true;
                            break;
                        }
                        if($isMapItem)break;
                    }
                    if (!$isMapItem) {
                        return $third_tool_name.'--'.$third_std_num.'--'.$item['projectname'] .'--'. $item['projecttypeid'] .'--缺少映射关系！';
                    }
                }
            //+++++++++++ 检测项目检测 对应主项目id和实际项目id end +++++++++++++++++++++
            $data = $this->getOrgData($v['departmentid']);
            $third_org_id = $third_org_name = '-';
            foreach($data as $type => $values){
                foreach ($values as $value) {
                    if ($type == 0) {
                        $third_org_id .= $value.'-';
                    }else{
                        $third_org_name .= $value.'-';
                    }
                }
            }
            $third_org_name = trim($third_org_name,'-');
            // dd($third_org_id , $third_org_name, $v);
            $inData[] = [
                'std_id'=>$std_id,
                'std_num'=>$stdMap['sys_name'],
                'third_id'=>$this->thirdId,
                'third_pk_id'=>$v['id'],
                'third_book_id'=>$v['testid'],
                'third_id2'=>$rfid,
                'third_tool_id'=>$v['categoryid'],
                'third_tool_name'=>$third_tool_name,
                'third_std_num'=>$v['standardcode'],
                'tool_id'=>$tool_id,
                'tool_name'=>$toolMap['sys_name'],
                'item_ids'=>implode(',',array_column($sysItems,'item_id')),
                'item_names'=>implode(',',array_column($sysItems,'item_name')), //把所有的项目名称都写上，方便页面展示
                'third_item_type_ids'=>implode(',',$projecttypeids),  //我方项目id-映射主项目类型id
                'third_item_ids'=>implode(',',$projectids),  //我方项目id-实际项目id
                'third_item_names'=>implode(',',$projectname),  //实际项目名称
                'guige_xinghao'=>array_get($v,'specification',''),
                'third_voltage'=>$third_vol,
                'voltage'=>$sys_vol,
                'vol_id'=>$vol_id,
                'self_num'=>$rfid,
                'third_org_id'=>$third_org_id,
                'third_org_name'=>$third_org_name,
                'manufacturer'=>array_get($v,'manufacturername',''),
            ];
            // dd($inData);
            $total += 1;
        }
        // dd($inData);
        $res = DB::table('a_third_data')->insert($inData);
        return $res ? $total : 0;
    }

    private function getUpSampleParam($sampleId){
        $thirdMap = $this->thirdMap;
        $itemMaps = $thirdMap[4];
        unset($itemMaps['third']);
        $std_tool_item_rel_ids = array_column($itemMaps,'sys_id');
        // dd($itemMaps);
        $newItemMaps = array_combine($std_tool_item_rel_ids, $itemMaps);
        $testList = [];
        $itemRelRes = DB::table('a_item_data as a')
            ->leftJoin('a_sample_info as b','a.sample_info_id','=','b.id')
            ->leftJoin('a_contract_gaiyao as c','b.contract_gaiyao_id','=','c.id')
            ->leftJoin('a_std_tool_item_rel as d',function ($query)
            {
                $query->on('c.std_id','=','d.std_id')->on('c.tool_id','=','d.tool_id')->on('a.item_id','=','d.testitem_id');
            })
            ->where('a.sample_info_id',$sampleId)
            ->pluck('a.res','d.id')->toArray();
        $third_data = DB::table('a_third_data as a')
            ->leftJoin('a_sample_info as b','a.bar_code','=','b.bar_code')
            ->where('b.id',$sampleId)
            ->first();
        foreach ($itemRelRes as $std_tool_item_rel_id => $res) {
            if (in_array($std_tool_item_rel_id,$std_tool_item_rel_ids)) {
                $item_third_id2 = array_get($newItemMaps[$std_tool_item_rel_id],'third_id2','');
                if (!$item_third_id2) {
                    $item_sys_name = array_get($newItemMaps[$std_tool_item_rel_id],'sys_name','');
                    return $item_sys_name.'没找到项目ID对照关系！';
                }
                $testInput = [
                    'testId'=>$third_data->third_book_id,
                    'rfid'=>$third_data->third_id2,
                    'projectTypeId'=>$item_third_id2,
                    'projectId'=>'',
                    'isPass'=> $res==1 ? true : ($res==0 ? false : null), //判定项目结论
                    'testValue'=>0,
                    'duration'=>0,
                    'pressurizationTimes'=>0,
                    'leakageVoltage'=>0,
                    'leakageCurrent'=>0,
                    'leakageTime'=>0,
                    'sectionalArea'=>0,
                    'shielding'=>0,
                    'speed'=>0,
                ];
                $third_item_ids = explode(',',$third_data->third_item_ids);
                foreach ($third_item_ids as $third_item_id) {
                    list($std_tool_item_rel_id2,$third_item_id2) = explode('-',
                        $third_item_id);
                    if ($std_tool_item_rel_id2 == $std_tool_item_rel_id) {
                        $testInput['projectId'] = $third_item_id2;   //带电作业系统实际项目id
                        break;
                    }
                }
                $testList[$std_tool_item_rel_id] = $testInput;
            }
        }
        $mapKeys = $thirdMap[5];
        unset($mapKeys['third']);
        $mapKeys = collect($mapKeys)->keyBy('sys_id')->toArray();
        $inputDatas = DB::table('a_input_data as a')
            ->leftJoin('a_testdata_key as b','a.testdata_key_id','=','b.id')
            ->where('a.sample_info_id',$sampleId)
            ->select('a.*','b.std_tool_item_rel_id')
            ->get()->toArray();
        if(!$inputDatas){
            return '没有可以上传的数据';
        }
        foreach($inputDatas as $k => $input){
            $toUp = array_get($mapKeys,$input->testdata_key_id,[]);
            if (!$toUp || !$toUp['third_name']) {
                continue;
            }
            $input = (object)array_merge((array)$input,$toUp);
            if ($input->formula == 'class') {
                $input->val = $input->class;
            }
            $bei = $input->times ?: 1;
            $testList[$input->std_tool_item_rel_id][$input->third_name] = (floatval($input->val) * $bei) ?: 0;
        }
        return array_values($testList);
    }

    //3、提交待检工具试验信息，跟客户沟通 通过 批次id，RFID，项目id 传数据
    public function saveGqjBookTestInfo($thirdMap){
        $this->thirdMap = $thirdMap;
        $request = request();
        $sampleIds  = request('sample_ids',[]);//获取要上传的实验数据的ID
        $params = [];
        foreach ($sampleIds as $sampleId) {
            $param = $this->getUpSampleParam($sampleId);
            if(!is_array($param)){
                return $param;
            }
            $params = array_merge($params,$param);
        }
        return $this->requestData(['api'=>'/api/testdata/submitinfo','params'=>$params],function ($data)
        {
            return $data == 200 ? 1 : $data;
        });
    }

    //4、试验类型(项目)、试验数据对照表
    public function getTestItems(){
        //$ary下标是试验类型id：projectTypeId
        $ary = [
            '01'=>[
                'name'=>'表面工频耐压试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                ]
            ],
            '02'=>[
                'name'=>'操作冲击耐压试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'pressurizationTimes'=>'加压次数',
                ]
            ],
            '03'=>[
                'name'=>'成组直流电阻试验',
                'upload'=>[
                    'sectionalArea'=>'截面积mm²',
                    'testValue'=>'电阻mΩ',
                ]
            ],
            '04'=>[
                'name'=>'冲击性能试验',
                'upload'=>[
                    'testValue'=>'冲击力N',
                ]
            ],
            '05'=>[
                'name'=>'电阻试验和屏蔽效率试验',
                'upload'=>[
                    'testValue'=>'电阻mΩ',
                    'shielding'=>'屏蔽效率dB',
                ]
            ],
            '06'=>[
                'name'=>'复合气瓶检查',
                'upload'=>[
                    'testValue'=>'压力%',
                    'duration'=>'时长s',
                ]
            ],
            '07'=>[
                'name'=>'工频干闪试验',
                'upload'=>[]
            ],
            '08'=>[
                'name'=>'工频耐压及泄漏电流试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                    'leakageCurrent'=>'泄漏电流mA',
                ]
            ],
            '09'=>[
                'name'=>'工频耐压试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                ]
            ],
            '10'=>[
                'name'=>'检查（外观及尺寸）',
                'upload'=>[]
            ],
            '11'=>[
                'name'=>'静负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'duration'=>'时长s',
                ]
            ],
            '12'=>[
                'name'=>'静抗弯负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'duration'=>'时长s',
                ]
            ],
            '13'=>[
                'name'=>'绝缘强度试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                ]
            ],
            '14'=>[
                'name'=>'空载动作冲击性能试验',
                'upload'=>[]
            ],
            '15'=>[
                'name'=>'耐穿刺性能试验',
                'upload'=>[]
            ],
            '16'=>[
                'name'=>'佩戴检查',
                'upload'=>[]
            ],
            '17'=>[
                'name'=>'屏蔽效率试验',
                'upload'=>[
                    'duration'=>'时长s',
                    'shielding'=>'屏蔽效率dB',
                ]
            ],
            '18'=>[
                'name'=>'启动电压试验',
                'upload'=>[
                    'testValue'=>'启动电压kV',
                ]
            ],
            '19'=>[
                'name'=>'泄漏电流试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                    'leakageCurrent'=>'泄漏电流mA',
                ]
            ],
            '20'=>[
                'name'=>'整体静负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'duration'=>'时长s',
                ]
            ],
            '21'=>[
                'name'=>'直流电阻试验',
                'upload'=>[
                    'testValue'=>'电阻mΩ',
                ]
            ],
            '22'=>[
                'name'=>'动负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'pressurizationTimes'=>'试验次数',
                ]
            ],
            '23'=>[
                'name'=>'动抗弯负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'duration'=>'时长s',
                ]
            ],
            '24'=>[
                'name'=>'间隙调整与放电试验',
                'upload'=>[]
            ],
            '25'=>[
                'name'=>'静抗扭负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'duration'=>'时长s',
                ]
            ],
            '26'=>[
                'name'=>'压力与流量试验',
                'upload'=>[
                    'testValue'=>'压力kPa',
                    'Speed'=>'流量L/min',
                ]
            ],
            '27'=>[
                'name'=>'整组试验',
                'upload'=>[
                    'testValue'=>'水柱长度cm',
                ]
            ],
            '28'=>[
                'name'=>'直流耐压试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                ]
            ],
            '29'=>[
                'name'=>'额定荷载全工况试验',
                'upload'=>[]
            ],
            '30'=>[
                'name'=>'扣带强力试验',
                'upload'=>[]
            ],
        ];
        return $ary;
    }

    // 5、获取基础数据信息 type:类型 1 工具分类  2 电压等级
    public function getToolVols($type=1){
        $url = $this->BaseUrl.'/api/testdata/getbaseitems';
        $postData = [
            'type'=>$type,
        ];
        $postData = json_encode($postData);
        $res = deCurl($url, $postData);
        if ($res['statusCode'] == 200 && $res['successed'] === true) {
            return $res['data'];
        }
    }
    private function getVolClass($type){
        return DB::table('a_voltage_class')->where('type',$type)->get()->keyBy(function ($item) {
            // dd($item);
            return $item->std_id.'-'.$item->tool_id.'-'.$item->val;
        })->toArray();
    }

}
